package Solution;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class problem015 {

    public List<List<Integer>> threeSum(int[] nums) {
        //数组排序
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (num > 0) {
                break;
            }
            if(i>0&&nums[i]==nums[i-1]){
                continue;
            }
            int l = i + 1;
            int r = nums.length - 1;
            while (l < r) {
                int sum = nums[l] + nums[r] + num;
                if (sum == 0) {
                    result.add(Arrays.asList(num, nums[l], nums[r]));
                    l++;
                    r--;
                    while (l<r&&nums[l-1] == nums[l]) {
                        l++;
                    }
                    while (l<r&&nums[r+1] == nums[r]) {
                        r--;
                    }
                } else if (sum > 0) {
                    r--;
                } else {
                    l++;
                }

            }
        }
        return result;
    }

    @Test
    public void test(){
        int[] nums=new int[]{0,0,0};
        threeSum(nums);
    }
}
